<template>
  <div class="container">
    <el-card>
      <div slot="header">
        <span style="font-weight: 700; font-size: 22px">重置密码</span>
      </div>
       <el-form ref="userForm" :model="userForm" :rules="rules" label-width="90px">
        <el-form-item label="原密码" prop="old_pwd">
          <el-input placeholder="请输入原密码" type="password" v-model="userForm.old_pwd" style="width:40%"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="new_pwd">
          <el-input placeholder="请输入新密码" type="password" v-model="userForm.new_pwd" style="width:40%"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="re_pwd">
          <el-input placeholder="请确认密码" type="password" v-model="userForm.re_pwd" style="width:40%"></el-input>
        </el-form-item>
        <el-form-item label-width="60px">
          <el-button type="primary" size="small" @click="btnOK">修改密码</el-button>
          <el-button type="info" plain @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { updatePwd } from '@/api/user'
export default {
  name: 'baseInfo',
  data () {
    const checkRePassword = (rule, value, callback) => {
      if (value !== this.userForm.new_pwd) {
        return callback(new Error('两次密码必须一致'))
      } else {
        // 必须返回callback() 否则表单校验失败
        return callback()
      }
    }
    return {
      userForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rules: {
        old_pwd: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在6-15之间', trigger: 'blur' }

        ],
        re_pwd: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: checkRePassword, trigger: 'blur' }

        ]
      }
    }
  },
  methods: {
    async btnOK () {
      await this.$refs.userForm.validate()
      await updatePwd(this.userForm)
      this.$message.success('密码修改成功,请重新登录')
      this.$store.dispatch('user/logout')
      location.reload()
    },
    reset () {
      this.userForm = {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      }
      this.$refs.userForm.resetFields()
    }
  }
}
</script>

<style>

</style>
